package cn.codeforfun.material;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/2/16 0016.
 */
@Controller
@RequestMapping("/material")
public class MaterialController {
    @Autowired
    private MaterialService materialService;

    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public void download(@PathVariable Long id, HttpServletResponse response) throws Exception {
        FileInputStream fileIs = null;
        Material mater = materialService.findOne(id);
        OutputStream outStream = null;
        try {
            fileIs = new FileInputStream(mater.getPath() + File.separator + mater.getFileName());
            int i = fileIs.available(); // 得到文件大小
            byte data[] = new byte[i];
            fileIs.read(data); // 读数据
            response.setContentType("image/*"); // 设置返回的文件类型
            response.setHeader("Content-Disposition", "attachment; filename=" + mater.getFileName());
            outStream = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
            outStream.write(data); // 输出数据
            outStream.flush();
            outStream.close();
            fileIs.close();
        } catch (Exception e) {
            return;
        } finally {
            if (outStream != null)
                outStream.close();
            if (fileIs != null)
                fileIs.close();
        }


    }
}
